package spring.framework.core.io;

import cn.hutool.core.lang.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author fun.pengzh
 * @class spring.framework.core.io.UrlResource
 * @desc
 * @since 2021-11-25
 */
public class UrlResource implements Resource {

    private URL url;

    private String urlStr;

    public UrlResource(String url) throws MalformedURLException {
        this.url = new URL(url);
        this.urlStr = url.toLowerCase();
    }

    public UrlResource(URL url) {
        Assert.notNull(url, "url can not be null");
        this.url = url;
        this.urlStr = url.toString();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof HttpURLConnection) {
            ((HttpURLConnection) urlConnection).disconnect();
        }
        return urlConnection.getInputStream();
    }

    public String getUrlStr() {
        return urlStr;
    }
}
